package com.triangle.cashier.tools;

import android.content.res.Resources;

import java.math.BigDecimal;


/**
 * 通用单位转换
 * Created by  on 14-11-6.
 */
public class Utils {
    /**
     * dp转px
     *
     * @param resources resources
     * @param dp        dp
     * @return px
     */
    public static float dp2px(Resources resources, float dp) {
        final float scale = resources.getDisplayMetrics().density;
        return dp * scale + 0.5f;
    }

    /**
     * sp转px
     *
     * @param resources resources
     * @param sp        sp
     * @return px
     */
    public static float sp2px(Resources resources, float sp) {
        final float scale = resources.getDisplayMetrics().scaledDensity;
        return sp * scale;
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Resources resources, float pxValue) {
        final float scale = resources.getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    public static float double2Float(double f) {
        int scale = 1;//设置位数
        int roundingMode = 4;//表示四舍五入，可以选择其他舍值方式，例如去尾，等等.
        BigDecimal bd = new BigDecimal(f);
        bd = bd.setScale(scale, roundingMode);
        return bd.floatValue();
    }

}
